<!-- 企业管理查看页面 -->
<template>
    <el-dialog :draggable="true" v-model="dialogVisible" :width="'80%'" :title="dialogTitle" :max-height="`90vh`"
        :close-on-click-modal="false" @close="handleClose">

        <div class="dialog-container">
            <el-tabs v-model="activeTab">
                <el-tab-pane label="基本信息" name="base">
                    <el-descriptions :column="2" :border="true" label-width="200px">
                        <el-descriptions-item label="企业名称" width="35%">
                            {{ enterpriseForm.enterpriseName }}
                        </el-descriptions-item>
                        <el-descriptions-item label="企业信用代码" width="35%">
                            {{ enterpriseForm.enterpriseCreditCode === ''
                                || enterpriseForm.enterpriseCreditCode === null
                                || enterpriseForm.enterpriseCreditCode === undefined
                                ? "暂无"
                                : enterpriseForm.enterpriseCreditCode }}
                        </el-descriptions-item>
                        <el-descriptions-item label="所属行业">
                            {{
                                enterpriseForm.enterpriseIndustry === 'information_technology' ? '信息技术' :
                                    enterpriseForm.enterpriseIndustry === 'financial_services' ? '金融服务' :
                                        enterpriseForm.enterpriseIndustry === 'manufacturing' ? '制造业' :
                                            enterpriseForm.enterpriseIndustry === 'healthcare' ? '医疗健康' :
                                                enterpriseForm.enterpriseIndustry === 'education' ? '教育培训' :
                                                    enterpriseForm.enterpriseIndustry === 'culture_media' ? '文化传媒' :
                                                        enterpriseForm.enterpriseIndustry === 'retail_trade' ? '零售贸易' :
                                                            enterpriseForm.enterpriseIndustry === 'logistics' ? '物流运输' :
                                                                enterpriseForm.enterpriseIndustry === 'catering_accommodation' ? '餐饮住宿' : '其他'
                            }}
                        </el-descriptions-item>
                        <el-descriptions-item label="企业类型">
                            {{
                                enterpriseForm.enterpriseType === 'limited_liability_company' ? '有限责任公司' :
                                    enterpriseForm.enterpriseType === 'joint_stock_company' ? '股份有限公司' :
                                        enterpriseForm.enterpriseType === 'sole_proprietorship' ? '个人独资企业' :
                                            enterpriseForm.enterpriseType === 'partnership' ? '合伙企业' :
                                                enterpriseForm.enterpriseType === 'state_owned' ? '国有企业' :
                                                    enterpriseForm.enterpriseType === 'foreign_owned' ? '外资企业' : '其他'
                            }}
                        </el-descriptions-item>
                        <el-descriptions-item label="法定代表人">
                            {{ enterpriseForm.enterpriseLegalRepresentative }}
                        </el-descriptions-item>
                        <el-descriptions-item label="法人身份证号">
                            {{ enterpriseForm.enterpriseLegalIdCard }}
                        </el-descriptions-item>
                        <el-descriptions-item label="联系人">
                            {{ enterpriseForm.enterpriseContactPerson }}
                        </el-descriptions-item>
                        <el-descriptions-item label="联系人电话">
                            {{ enterpriseForm.enterpriseContactPhone }}
                        </el-descriptions-item>
                        <el-descriptions-item label="联系人邮箱">
                            {{ enterpriseForm.enterpriseContactEmail }}
                        </el-descriptions-item>
                        <el-descriptions-item label="注册日期">
                            {{ enterpriseForm.enterpriseRegistDate }}
                        </el-descriptions-item>
                        <el-descriptions-item label="注册资本">
                            {{ enterpriseForm.enterpriseRegisteredCapital }}
                        </el-descriptions-item>
                        <el-descriptions-item label="资本币种">
                            {{ enterpriseForm.enterpriseCapitalCurrency }}
                        </el-descriptions-item>
                        <el-descriptions-item label="企业简介">
                            <el-tooltip :content="enterpriseForm.enterpriseIntro" placement="top">
                                <div class="intro-content" ref="introRef">
                                    {{ enterpriseForm.enterpriseIntro }}
                                </div>
                            </el-tooltip>
                        </el-descriptions-item>
                        <el-descriptions-item label="官网地址">
                            <!-- 处理地址为空的情况 -->
                            <template v-if="enterpriseForm.enterpriseOfficialWebsite">
                                <!-- 补全协议（如果地址不含http/https），确保链接有效 -->
                                <a :href="formatUrl(enterpriseForm.enterpriseOfficialWebsite)" target="_blank"
                                    rel="noopener noreferrer" class="link-style">
                                    {{ enterpriseForm.enterpriseOfficialWebsite }}
                                </a>
                            </template>
                            <!-- 地址为空时显示默认文本 -->
                            <span v-else>暂无</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="状态">
                            <el-tag type="warning" v-if="enterpriseForm.enterpriseStatus == 'pending'">
                                审核中
                            </el-tag>
                            <el-tag type="success" v-if="enterpriseForm.enterpriseStatus == 'approved'">
                                已入驻
                            </el-tag>
                            <el-tag type="error" v-if="enterpriseForm.enterpriseStatus == 'moved_out'">
                                已离园
                            </el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item label="是否关注">
                            <el-tag type="success" v-if="enterpriseForm.enterpriseIsFollowed">
                                {{ enterpriseForm.enterpriseIsFollowed ? "关注" : "未关注" }}
                            </el-tag>
                            <el-tag type="warning" v-if="!enterpriseForm.enterpriseIsFollowed">
                                {{ enterpriseForm.enterpriseIsFollowed ? "关注" : "未关注" }}
                            </el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item label="企业信息创建时间">
                            {{ enterpriseForm.createdAt }}
                        </el-descriptions-item>
                        <el-descriptions-item label="企业信息更新时间">
                            {{ enterpriseForm.updatedAt }}
                        </el-descriptions-item>
                    </el-descriptions>
                </el-tab-pane>

                <el-tab-pane label="入驻信息" name="location">
                    <div v-if="sortedLocationData && sortedLocationData.length > 0">
                        <el-table :data="sortedLocationData" :border="true" style="width: 100%;"
                            :span-method="arraySpanMethod">
                            <el-table-column prop="parkName" label="所属园区" :align="'center'"></el-table-column>
                            <el-table-column prop="buildingName" label="楼栋" :align="'center'"></el-table-column>
                            <el-table-column prop="floor" label="楼层" :align="'center'">
                                <template #default="scope">
                                    <el-tag>
                                        {{ scope.row.floor }}层
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="room" label="房间" :align="'center'">
                                <template #default="scope">
                                    <el-tag>
                                        {{ scope.row.room }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="useArea" label="使用面积" :align="'center'"></el-table-column>
                            <el-table-column prop="propertyArea" label="物业面积" :align="'center'"></el-table-column>
                        </el-table>
                        <div class="total-area"
                            style="margin-top: 16px; display: flex; justify-content: flex-end; gap: 20px;">
                            <el-tag type="success">使用总面积: {{ totalUseArea }}</el-tag>
                            <el-tag type="success">物业总面积: {{ totalPropertyArea }}</el-tag>
                        </div>
                    </div>
                    <div v-else-if="!sortedLocationData || sortedLocationData.length == 0">
                        无入住信息
                    </div>
                </el-tab-pane>

                <el-tab-pane label="入住合同" name="contract">
                    <div
                        v-if="enterpriseForm.enterpriseContractPojoList && enterpriseForm.enterpriseContractPojoList.length > 0">
                        <el-form-item>
                            <el-button type="success" @click="handlePreviewContract">查看合同</el-button>
                            <el-button type="warning" @click="handleDownContract">
                                下载合同
                            </el-button>
                        </el-form-item>
                        <el-descriptions :column="2" :border="true" label-width="200px">
                            <el-descriptions-item label="合同编号" width="35%">
                                {{ enterpriseForm.enterpriseContractPojoList[0].contractNumber }}
                            </el-descriptions-item>
                            <el-descriptions-item label="合同签订日期" width="35%">
                                {{ enterpriseForm.enterpriseContractPojoList[0].contractSignDate }}
                            </el-descriptions-item>
                            <el-descriptions-item label="合同生效日期">
                                {{ enterpriseForm.enterpriseContractPojoList[0].contractStartDate }}
                            </el-descriptions-item>
                            <el-descriptions-item label="合同到期日期">
                                {{ enterpriseForm.enterpriseContractPojoList[0].contractEndDate }}
                            </el-descriptions-item>
                            <el-descriptions-item label="租金">
                                {{ enterpriseForm.enterpriseContractPojoList[0].contractRent }}
                            </el-descriptions-item>
                            <el-descriptions-item label="押金">
                                {{ enterpriseForm.enterpriseContractPojoList[0].contractDeposit }}
                            </el-descriptions-item>
                            <el-descriptions-item label="付款周期">
                                <el-tag>
                                    {{
                                        enterpriseForm.enterpriseContractPojoList[0].contractPaymentCycle === 'monthly' ?
                                            '每月' :
                                            enterpriseForm.enterpriseContractPojoList[0].contractPaymentCycle === 'quarterly' ?
                                                '每季度' :
                                                enterpriseForm.enterpriseContractPojoList[0].contractPaymentCycle === 'yearly' ?
                                                    '每年' :
                                                    '无数据'
                                    }}
                                </el-tag>
                            </el-descriptions-item>
                            <el-descriptions-item label="合同状态">
                                <el-tag>
                                    {{
                                        enterpriseForm.enterpriseContractPojoList[0].contractStatus === 'draft' ? '草稿' :
                                            enterpriseForm.enterpriseContractPojoList[0].contractStatus === 'signed' ? '已签订' :
                                                enterpriseForm.enterpriseContractPojoList[0].contractStatus === 'expired' ? '已过期' :
                                                    enterpriseForm.enterpriseContractPojoList[0].contractStatus === 'terminated' ? '已终止'
                                                        :
                                                        '无数据'
                                    }}
                                </el-tag>
                            </el-descriptions-item>
                            <el-descriptions-item label="合同内容">
                                <el-tooltip :content="enterpriseForm.enterpriseContractPojoList[0].contractNotes"
                                    placement="top">
                                    <div class="intro-content" ref="introRef">
                                        {{ enterpriseForm.enterpriseContractPojoList[0].contractNotes }}
                                    </div>
                                </el-tooltip>
                            </el-descriptions-item>
                            <el-descriptions-item label="文件名">
                                {{ enterpriseForm.enterpriseContractPojoList[0].contractFileName }}
                            </el-descriptions-item>
                            <el-descriptions-item label="上传时间">
                                {{ enterpriseForm.enterpriseContractPojoList[0].createdAt }}
                            </el-descriptions-item>
                            <el-descriptions-item label="更新时间">
                                {{ enterpriseForm.enterpriseContractPojoList[0].updatedAt }}
                            </el-descriptions-item>
                        </el-descriptions>
                    </div>
                    <div
                        v-else-if="!enterpriseForm.enterpriseContractPojoList || enterpriseForm.enterpriseContractPojoList.length == 0">
                        无合同信息
                    </div>

                </el-tab-pane>

                <el-tab-pane label="资质文件" name="qualification">
                    <div
                        v-if="enterpriseForm.enterpriseQualificationPojos && enterpriseForm.enterpriseQualificationPojos.length > 0">
                        <!-- 水平排列容器：el-row + 适当间距 -->
                        <el-row :gutter="20" class="card-container">
                            <!-- 循环渲染卡片，每个卡片用el-col包裹 -->
                            <el-col v-for="(item, index) in enterpriseForm.enterpriseQualificationPojos" :key="index"
                                :span="12" :xs="24">
                                <el-card class="horizontal-card" hoverable>
                                    <div class="card-content">
                                        <el-descriptions :column="1" :border="true" label-width="200px">
                                            <el-descriptions-item label="文件名">
                                                {{ item.qualificationFileName }}
                                            </el-descriptions-item>
                                            <el-descriptions-item label="文件类型">

                                                <el-tag>
                                                    {{
                                                        item.qualificationFileType ===
                                                            'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                                                            ? '.docx'
                                                            :
                                                            item.qualificationFileType ===
                                                                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                                                                ? '.xlsx' :
                                                                item.qualificationFileType ===
                                                                    'application/vnd.openxmlformats-officedocument.presentationml.presentation'
                                                                    ?
                                                                    '.pptx' :
                                                                    item.qualificationFileType === 'application/msword' ? '.doc' :
                                                                        item.qualificationFileType === 'application/vnd.ms-excel' ? '.xls' :
                                                                            item.qualificationFileType === 'application/vnd.ms-powerpoint' ?
                                                                                '.ppt' :
                                                                                item.qualificationFileType
                                                    }}
                                                </el-tag>
                                            </el-descriptions-item>
                                            <el-descriptions-item label="文件大小">
                                                {{ formatFileSize(item.qualificationFileSize) }}
                                            </el-descriptions-item>
                                            <el-descriptions-item label="上传时间">
                                                {{ item.createdAt }}
                                            </el-descriptions-item>
                                            <el-descriptions-item label="更新时间">
                                                {{ item.updatedAt }}
                                            </el-descriptions-item>

                                        </el-descriptions>
                                    </div>
                                    <template #footer>
                                        <el-button type="success"
                                            @click="handlePreviewQualification(item)">查看文件</el-button>
                                        <el-button type="warning" @click="handleDownQualification(item)">
                                            下载文件
                                        </el-button>
                                    </template>
                                </el-card>
                            </el-col>
                        </el-row>
                    </div>
                    <div
                        v-else-if="!enterpriseForm.enterpriseQualificationPojos || enterpriseForm.enterpriseQualificationPojos.length == 0">
                        无资质文件信息
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
        <!-- 底部操作区：固定在弹框底部 -->
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">关闭</el-button>
            </span>
        </template>

        <!-- 引入预览组件 -->
        <FilePreview :show="previewVisible" :file-info="currentFile" @update:show="(val) => previewVisible = val" />

    </el-dialog>
</template>
<script setup>
import { ref, reactive, watch, computed } from 'vue';
import { downloadContract } from '@/api/contract'
import FilePreview from '@/components/file/FilePreview.vue';

const enterpriseForm = reactive({
    enterpriseId: null,
    enterpriseName: '',//企业名称
    enterpriseCreditCode: '',//企业信用代码
    enterpriseIndustry: '',//所属行业
    enterpriseType: '',//企业类型
    enterpriseLegalRepresentative: '',//法定代表人
    enterpriseLegalIdCard: '',//法人身份证号
    enterpriseContactPerson: '',//联系人
    enterpriseContactPhone: '',//联系人电话
    enterpriseContactEmail: '',//联系人邮箱
    enterpriseRegistDate: '',//注册日期
    enterpriseRegisteredCapital: '',//注册资本
    enterpriseCapitalCurrency: '人民币',
    enterpriseIntro: '',//企业简介
    enterpriseOfficialWebsite: '',//官网地址
    enterpriseStatus: 'pending',//状态
    enterpriseIsFollowed: false,//是否关注
    isDeleted: null,//是否删除
    parkInfo: {},//园区信息
    parkBuilding: {},//楼栋信息
    enterpriseContractPojoList: [],//合同信息
    enterpriseRoomPojos: [],//绑定房间信息
    enterpriseQualificationPojos: [],//资质信息
    createdAt: null,
    updatedAt: null,
});
// 接收父组件参数
const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    enterprise: {
        type: Object,
        default: () => ({})
    }
});
const dialogVisible = ref(props.visible);
const emit = defineEmits(['close']);
const activeTab = ref('base');
const dialogTitle = ref("企业信息查看")

// 关闭对话框
const handleClose = () => {
    emit('close');
};
// 预览状态
const previewVisible = ref(false);
const currentFile = ref({
    bucketName: 'park',
    objectName: '',
    fileName: ''
});

//-------------------------------------------------企业基本信息-------------------------------------

// 格式化URL，补全协议
const formatUrl = (url) => {

    if (!url) return '';
    // 判断是否已包含http/https协议
    if (!/^https?:\/\//i.test(url)) {
        return `https://${url}`; // 补全https协议
    }
    return url;
};
//-------------------------------------------------企业基本信息结束-------------------------------------

//-----------------------------------------------入住信息数据处理----------------------------------------
//  格式化数据（添加园区、楼栋，基于排序后的数据）
const locationData = computed(() => {
    return enterpriseForm.enterpriseRoomPojos.map(item => ({
        parkName: enterpriseForm.parkInfo.name,
        buildingName: enterpriseForm.parkBuilding.name,
        floor: item.parkRoom.floor,
        room: item.parkRoom.roomNumber,
        useArea: item.enterpriseUseArea,
        propertyArea: item.enterprisePropertyArea,
    }));
});
// 排序后的数据：按楼层数字升序
const sortedLocationData = computed(() => {
    return [...locationData.value].sort((a, b) => {
        const floorA = parseInt(a.floor, 10);
        const floorB = parseInt(b.floor, 10);
        return floorA - floorB;
    });
});
// 3. 计算合并配置（所属园区 + 楼栋 + 楼层）
const getMergeConfig = () => {
    const dataLength = sortedLocationData.value.length;
    // 所属园区：合并所有行
    const parkMerge = { rowspan: dataLength, colspan: 1 };
    // 楼栋：合并所有行（因所有行楼栋均为“BB”）
    const buildingMerge = { rowspan: dataLength, colspan: 1 };
    // 楼层：合并连续相同的楼层
    // 初始化变量
    const floorMergeConfig = []; // 存储合并配置：{ startIndex: 起始行索引, rowspan: 合并行数 }
    let currentFloor = null; // 当前楼层
    let startIndex = 0; // 当前楼层的起始行索引
    let count = 0; // 当前楼层的累计行数

    sortedLocationData.value.forEach((item, index) => {
        if (item.floor === currentFloor) {
            // 同一楼层：累计行数
            count++;
        } else {
            // 新楼层：记录上一个楼层的合并信息（如果不是第一行）
            if (currentFloor !== null) {
                floorMergeConfig.push({
                    startIndex: startIndex,
                    rowspan: count
                });
            }
            // 更新当前楼层信息
            currentFloor = item.floor;
            startIndex = index; // 新楼层的起始行是当前索引
            count = 1; // 重置行数为1（当前行）
        }

        // 处理最后一行：循环结束后补充最后一个楼层的合并信息
        if (index === sortedLocationData.value.length - 1) {
            floorMergeConfig.push({
                startIndex: startIndex,
                rowspan: count
            });
        }
    });

    return { parkMerge, buildingMerge, floorMergeConfig };
};

// 4. 表格合并单元格方法
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
    const { parkMerge, buildingMerge, floorMergeConfig } = getMergeConfig();

    // 合并“所属园区”列（第1列，columnIndex = 0）
    if (columnIndex === 0) {
        return rowIndex === 0 ? parkMerge : { rowspan: 0, colspan: 0 };
    }
    // 合并“楼栋”列（第2列，columnIndex = 1）
    else if (columnIndex === 1) {
        return rowIndex === 0 ? buildingMerge : { rowspan: 0, colspan: 0 };
    } else if (columnIndex === 2) {
        // 查找当前行是否是某个合并组的起始行
        const target = floorMergeConfig.find(item => item.startIndex === rowIndex);
        if (target) {
            // 是起始行：返回合并行数
            return { rowspan: target.rowspan, colspan: 1 };
        } else {
            // 不是起始行：不显示（被合并）
            return { rowspan: 0, colspan: 0 };
        }
    }
    // 其他列不合并
    return null;
};
// 计算总面积
const totalUseArea = computed(() =>
    locationData.value.reduce((sum, item) => sum + item.useArea, 0).toFixed(2)
);
const totalPropertyArea = computed(() =>
    locationData.value.reduce((sum, item) => sum + item.propertyArea, 0).toFixed(2)
);
//-----------------------------------------------入住信息数据处理结束----------------------------------------


//-----------------------------------------------入住合同管理---------------------------------------------
const handleDownContract = () => {
    downloadContract(
        {
            contractId: enterpriseForm.enterpriseContractPojoList[0].contractId
        },
        'enterpriseContract/download-file'
    )
}

//预览合同
const handlePreviewContract = async () => {
    currentFile.value.fileName = enterpriseForm.enterpriseContractPojoList[0].contractFileName
    currentFile.value.objectName = enterpriseForm.enterpriseContractPojoList[0].contractFilePath
    previewVisible.value = true;

}
//-----------------------------------------------入住合同管理结束---------------------------------------------

//------------------------------------------------资质文件---------------------------------------------------
// 格式化文件大小（字节 → MB/KB）
const formatFileSize = (size) => {
    if (!size) return '0 KB';
    return size >= 1024 * 1024
        ? (size / (1024 * 1024)).toFixed(2) + ' MB'
        : (size / 1024).toFixed(2) + ' KB';
};
//下载文件
const handleDownQualification = (row) => {
    downloadContract(
        {
            enterpriseQualificationId: row.enterpriseQualificationId
        },
        'qualification/download-file'
    )
}

//预览文件
const handlePreviewQualification = (row) => {
    currentFile.value.fileName = row.qualificationFileName
    currentFile.value.objectName = row.qualificationFilePath
    previewVisible.value = true;
}
//------------------------------------------------资质文件结束---------------------------------------------------

// 监听visible变化
watch(
    () => props.visible,
    (newVal) => {
        dialogVisible.value = newVal;
    }
);

// 监听enterprise变化，初始化表单数据
watch(
    () => props.enterprise,
    (newVal) => {
        if (newVal && newVal.enterpriseId) {
            Object.keys(enterpriseForm).forEach(key => {
                if (key !== 'enterpriseRoomList' && newVal[key] !== undefined) {
                    enterpriseForm[key] = newVal[key];
                }
            });
            activeTab.value = 'base'
        }
        dialogTitle.value = enterpriseForm.enterpriseName
    },
    { immediate: true }
);

</script>
<style scoped>
.dialog-container {
    max-height: calc(90vh - 200px);
    overflow-y: auto;
    /* 内容超出时纵向滚动 */
    padding: 10px;
    /* 可选：增加内边距 */
}


/* 滚动条美化（可选） */
.dialog-content::-webkit-scrollbar {
    width: 6px;
}

.dialog-content::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
}

/* 底部操作区：自动右对齐（Element Plus 默认样式） */
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.link-style {
    color: #409eff;
    /* Element Plus主题色 */
    text-decoration: underline;
}

.link-style:hover {
    color: #66b1ff;
    /*  hover时颜色变浅 */
}

.intro-content {
    max-width: 600px;
    /* 限制宽度 */
    max-height: 48px;
    /* 限制高度（2行文字高度，根据字体大小调整） */
    overflow: hidden;
    /* 隐藏溢出内容 */
    text-overflow: ellipsis;
    /* 显示省略号 */
    display: -webkit-box;
    /* 弹性盒模型 */
    -webkit-line-clamp: 2;
    /* 最多显示2行 */
    -webkit-box-orient: vertical;
    /* 垂直排列 */
    white-space: normal;
    /* 允许换行 */
}
</style>